/**
 * @file Client.cpp
 * @author Frans Stijn
 * @brief Defines the functions declared in Client.h.
 */
#include "Client.h"

Client* Client::instance = NULL;

Client* Client::getInstance()
{
    if(instance == NULL) 
    {		
        instance = new Client(); 
	cout << "instance gemaakt" << endl;                   
    }
    return instance;
}

Client::Client()
{
	if(init() == -1)
	{
	cout << "init failed" << endl;
	exit(1);
	}
}

int Client:: init()
{
	servAddr.sin_family = AF_INET;
        servAddr.sin_addr.s_addr = htonl(INADDR_ANY);           
        servAddr.sin_port = htons(UDPPORT);

       if((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
       {
              perror("geen socket");
              return -1;
       }    

       if(bind(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) == -1)
       {
              perror("geen binding met poort");
              return -1;
       }
       return 0;
} 

void Client::run()
{
	socklen_t len; 
	len = sizeof(cliAddr);

       while(1)
       {	 

	lengte = recvfrom(sock, inbuf, INBUFLEN , 0, (struct sockaddr*)&cliAddr, &len);
	cout<<"ontvangen"<<endl;
	cout<<lengte<<endl;

       }
       close(sock);
}

bool Client::receive(RobotData *robot,RobotData *robotb, vector<Point> obstacles)
{


       if(lengte!=0)
       { 
	robotinfo robfo;
	int aantobs;


		
	memcpy((void*)&robfo,inbuf,sizeof(robotinfo));
	robot->set_robot(robfo.ax,robfo.ay,robfo.aa);
	robot->set_blikje(robfo.axc, robfo.ayc);
  	robot->set_garage(robfo.axg, robfo.ayg);

	robotb->set_robot(robfo.bx,robfo.by,robfo.ba);
	robotb->set_blikje(robfo.bxc, robfo.byc);
  	robotb->set_garage(robfo.bxg, robfo.byg);
	aantobs=(lengte-64)/4;


	if (! obstacles.empty())
		obstacles.clear();


	for(int i=0;i<(aantobs/2);i++)
	{
	Point blik(robfo.obs[0+(2*i)],robfo.obs[1+(2*i)]);
	obstacles.push_back(blik);
	
	}
//	cout << "ik kom hier" << endl;
	lengte=0;
              return true;                              
       }
       else
       {
              return false;             
       }
}


